package javaweb_work01.Listener;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

public class OnlineUser implements HttpSessionListener, ServletContextListener {
    //声明一个ServletCotex类型的引用记录当前在线用户数量
    ServletContext servletContext = null;
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        //初始化ServletContext
        servletContext = servletContextEvent.getServletContext();
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        //当ServletContext销毁时取值为0
        servletContext = null;
    }

    @Override
    public void sessionCreated(HttpSessionEvent httpSessionEvent) {
        //得到当前servletContext的属性值
        Integer count = (Integer) servletContext.getAttribute("count");
        //若属性值为空，则当前用户为第一个用户，设置servletContext的属性值为1
        if(null == count){
            servletContext.setAttribute("count",1);
        //否则属性值+1
        }else {
            ++count;
            servletContext.setAttribute("count",count);
        }
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
        //用户下线则session销毁，属性值-1
        Integer count = (Integer) servletContext.getAttribute("count");
        --count;
        servletContext.setAttribute("count",count);
    }
}
